package cn.com.unionlife.hy.media.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Service;

import cn.com.unionlife.hy.core.exception.BusinessException;
import cn.com.unionlife.hy.core.mybatis.HYRowBounds;
import cn.com.unionlife.hy.core.vo.BaseConditionVO;
import cn.com.unionlife.hy.core.vo.PaginationVO;
import cn.com.unionlife.hy.media.mapper.MediaMapper;
import cn.com.unionlife.hy.media.service.MediaQryService;
import cn.com.unionlife.hy.media.vo.MediaConditionVO;
import cn.com.unionlife.hy.media.vo.MediaVO;

@Service("mediaQryService")
public class MediaQryServiceImpl implements MediaQryService {

	@Resource(name = "mediaMapper")
	private MediaMapper mediaMapper;

	@Override
	public PaginationVO<MediaVO> findByCondition(MediaConditionVO condition)  throws BusinessException{
		if(condition == null){
			throw new BusinessException("查询条件不能为null");
		}
		if(StringUtils.isBlank(condition.getUserId())){
			throw new BusinessException("需要登录才能查询");
		}
		PaginationVO<MediaVO> retVal = new PaginationVO<MediaVO>();
		
		long total = mediaMapper.countByCondition(condition);
		
		int page = condition.getPageNum() > 0 ? condition.getPageNum() : 1;
		int pageSize = condition.getPageSize() > 0 ? condition.getPageSize() : BaseConditionVO.DEFAULT_PAGESIZE; 
		int offset = (page -1) * pageSize;
		int limit = pageSize;
		RowBounds rowBounds = new HYRowBounds(offset , limit);
		List<MediaVO> medias = mediaMapper.findByCondition(condition, rowBounds);
		
		retVal.setTotalCount((int) total);
		retVal.setValues(medias);
		retVal.setCurrentPage(page);
		retVal.setPageSize(pageSize);
		return retVal;
	}

	@Override
	public MediaVO getMediaById(Long id) throws BusinessException {
		return mediaMapper.getById(id);
	}
}
